package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Order;
import com.draven.mall.entity.Rider;
import com.draven.mall.service.DispatchService;
import com.draven.mall.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员订单调度控制器
 */
@RestController
@RequestMapping("/api/admin/order/dispatch")
public class AdminDispatchController {

    private static final Logger log = LoggerFactory.getLogger(AdminDispatchController.class);

    @Autowired
    private DispatchService dispatchService;
    
    @Autowired
    private OrderService orderService;

    /**
     * 手动分配订单给骑手
     */
    @PostMapping("/assign")
    public ApiResponse assignOrderToRider(@RequestParam Long orderId) {
        try {
            Long riderId = dispatchService.assignRider(orderId);
            if (riderId != null) {
                return ApiResponse.success("订单成功分配给骑手：" + riderId);
            } else {
                return ApiResponse.error("订单分配失败，可能没有可用骑手");
            }
        } catch (Exception e) {
            log.error("分配订单异常", e);
            return ApiResponse.error("分配订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试调度算法
     */
    @PostMapping("/test-algorithm")
    public ApiResponse testDispatchAlgorithm(
            @RequestParam Long orderId,
            @RequestParam(required = false, defaultValue = "1") Integer algorithmType) {
        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }
            
            Rider rider = dispatchService.assignRiderWithAlgorithm(order, algorithmType);
            if (rider != null) {
                return ApiResponse.success("使用算法" + algorithmType + "分配结果：骑手ID=" + rider.getId() + 
                        "，姓名=" + rider.getRealName());
            } else {
                return ApiResponse.error("分配失败，没有找到合适的骑手");
            }
        } catch (Exception e) {
            log.error("测试调度算法异常", e);
            return ApiResponse.error("测试算法失败: " + e.getMessage());
        }
    }
} 